<template>
  <div class="activity-form">
    <h2>{{ isEdit ? '编辑活动' : '添加活动' }}</h2>
    
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="form-container"
    >
      <el-form-item label="所属社团" prop="clubId">
        <el-select v-model="form.clubId" placeholder="请选择社团" filterable
                  :disabled="isEdit && !isAdmin">
          <el-option
            v-for="club in clubOptions"
            :key="club.id"
            :label="club.name"
            :value="club.id"
          ></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="活动标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入活动标题"></el-input>
      </el-form-item>
      
      <el-form-item label="活动地点" prop="location">
        <el-input v-model="form.location" placeholder="请输入活动地点"></el-input>
      </el-form-item>
      
      <el-form-item label="活动时间" prop="schedule">
        <el-date-picker
          v-model="form.schedule"
          type="datetime"
          placeholder="请选择活动时间"
          format="YYYY-MM-DD HH:mm:ss"
         value-format="YYYY-MM-DDTHH:mm:ss"
        ></el-date-picker>
      </el-form-item>
      
      <el-form-item label="活动描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="4"
          placeholder="请输入活动描述"
        ></el-input>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="goBack">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getActivityDetail, addActivity, updateActivity } from '@/api/activity'
import { getClubList } from '@/api/club'
import { useUserStore } from '@/store/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const formRef = ref(null)
const clubOptions = ref([])

// 用户信息
const userInfo = computed(() => userStore.userInfo)
const isAdmin = computed(() => userInfo.value.role === 'admin')
const isClubLeader = computed(() => userInfo.value.role === 'club_leader')

// 是否为编辑模式
const isEdit = computed(() => {
  return route.params.id !== undefined
})

// 表单数据
const form = reactive({
  clubId: null,
  title: '',
  location: '',
  schedule: '',
  description: ''
})

// 表单校验规则
const rules = reactive({
  clubId: [
    { required: true, message: '请选择社团', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入活动标题', trigger: 'blur' },
    { max: 255, message: '活动标题不能超过255个字符', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' },
    { max: 255, message: '活动地点不能超过255个字符', trigger: 'blur' }
  ],
  schedule: [
    { required: true, message: '请选择活动时间', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入活动描述', trigger: 'blur' }
  ]
})

// 加载社团列表
const loadClubs = async () => {
  try {
    let params = { pageSize: 1000 }
    
    // 如果是社团负责人且不是管理员，只能看到自己管理的社团
    if (isClubLeader.value && !isAdmin.value) {
      params.leaderId = userInfo.value.id
    }
    
    const res = await getClubList(params)
    if (res.data && res.code === 200) {
      clubOptions.value = res.data.list
      
      // 如果是社团负责人且不是管理员，默认选择第一个社团
      if (!isEdit.value && isClubLeader.value && !isAdmin.value && clubOptions.value.length > 0) {
        form.clubId = clubOptions.value[0].id
      }
    } else {
      ElMessage.error(res.message || '获取社团列表失败')
    }
  } catch (error) {
    console.error('获取社团列表出错:', error)
    ElMessage.error('获取社团列表失败')
  }
}

// 获取活动详情
const getActivityInfo = async (id) => {
  try {
    const res = await getActivityDetail(id)
    if (res.code === 200 && res.data) {
      // 填充表单数据
      form.clubId = res.data.clubId
      form.title = res.data.title
      form.location = res.data.location
      form.schedule = res.data.schedule
      form.description = res.data.description
      
      // 检查权限
      if (isClubLeader.value && !isAdmin.value) {
        // 检查是否是该社团的负责人
        const isLeader = clubOptions.value.some(club => 
          club.id === res.data.clubId && club.leaderId === userInfo.value.id
        )
        // if (!isLeader) {
        //   ElMessage.error('您无权编辑此活动')
        //   goBack()
        // }
      }
    } else {
      ElMessage.error(res.message || '获取活动信息失败')
      goBack()
    }
  } catch (error) {
    console.error('获取活动详情出错:', error)
    ElMessage.error('获取活动信息失败')
    goBack()
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (isEdit.value) {
      // 编辑活动
      const id = route.params.id
      const res = await updateActivity(id, form)
      if (res.code === 200) {
        ElMessage.success('更新成功')
        goBack()
      } else {
        ElMessage.error(res.message || '更新失败')
      }
    } else {
      // 添加活动
      const res = await addActivity(form)
      if (res.code === 200) {
        ElMessage.success('添加成功')
        goBack()
      } else {
        ElMessage.error(res.message || '添加失败')
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('表单数据不完整或格式不正确')
  }
}

// 返回上一页
const goBack = () => {
  router.push('/activities')
}

// 初始化
onMounted(() => {
  loadClubs()
  
  if (isEdit.value && route.params.id) {
    getActivityInfo(route.params.id)
  }
})
</script>

<style scoped>
.activity-form {
  padding: 20px;
}

.form-container {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style> 